//
//  LoginViewController.m
//  编程题1
//
//  Created by haoran on 16/3/30.
//  Copyright © 2016年 xuhaoran. All rights reserved.
//

#import "LoginViewController.h"
#import "SVProgressHUD.h"
#import "AFNetworking.h"

@interface LoginViewController ()
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;

@property (weak, nonatomic) IBOutlet UITextField *pwdTF;

/** 用户名 **/
@property (nonatomic, strong) NSString *userName;
/** 密码 **/
@property (nonatomic, strong) NSString *pwd;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (IBAction)loginBtnClick:(id)sender {
    //1.判断用户名
    if ([_userNameTF.text isEqualToString:@""]) {
        [SVProgressHUD showErrorWithStatus:@"请输入用用户名"];
        return;
    }
    _userName = _userNameTF.text;
    
    //2.判断密码
    if( [_pwdTF.text isEqualToString:@""]){
        [SVProgressHUD showErrorWithStatus:@"请输入用密码"];
        return;
    }
    _pwd = _pwdTF.text;
    
    //3.发送请求
    //黑色遮罩
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD showWithStatus:@"正在登录"];
    [self startLogin];
    
    
}
- (IBAction)backToRegBtnClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark ---- 发送网络请求
-(void)startLogin{
    //1.创建会话管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

    //创建字典,转载参数
    NSDictionary *dict =@{
                           @"name":_userName,
                           @"pwd":_pwd,
                           @"type":@"JSON"
                           };
    //2.发送POST请求上传文件
    /*
     第一个参数:请求路径(1不包含参数2?3NSString)
     第二个参数:字典
     第三个参数:progress 进度
     第四个参数:success 成功回调
     task :请求任务 task.response
     responseObject:响应体信息(内部已经完成了序列化处理.JSON)
     第五个参数:failure 失败的回调
     error:错误信息
     */
    manager.requestSerializer = [[AFJSONRequestSerializer alloc]init];
    
    
    [manager POST:@"http://api.liyaogang.com/login.php" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@--%@",[responseObject class],responseObject);
        //取出返回的信息
       
        NSString *temp = responseObject[@"message"];
        if ([temp containsString:@"success"]) {
            //3.回主线程,跳转到登陆界面
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [SVProgressHUD showSuccessWithStatus:@"登录成功"];
                [self performSegueWithIdentifier:@"login" sender:nil];
            });
        }
        else{
            //3.回主线程,跳转到登陆界面
            dispatch_async(dispatch_get_main_queue(), ^{
                
                [SVProgressHUD showErrorWithStatus:temp];                
            });
       }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"登录失败--%@",error);
    }];

}
@end
